package com.xyy.saas.payment.controller;

import com.xyy.saas.payment.callback.CallbackRunner;
import com.xyy.saas.payment.cores.enums.FBankPowerIdEnum;
import com.xyy.saas.payment.cores.enums.OpenAccountAuthorizeStatusEnum;
import com.xyy.saas.payment.cores.enums.OpenPayStatusEnum;
import com.xyy.saas.payment.cores.vo.CallbackResultVo;
import com.xyy.saas.payment.dao.model.*;
import com.xyy.saas.payment.service.*;
import com.xyy.saas.payment.util.JSONUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Objects;

@Slf4j
@RestController
@RequestMapping(value = {"/api/notify"})
public class AccountChangeController {
    @Resource
    private ThirdUserInfoService thirdUserInfoService;
    @Resource
    private OpenpayInfoService openpayInfoService;
    @Resource
    private ApplyOpenAccountStatusService applyOpenAccountStatusService;
    @Resource
    private ApplypayUserInfoService applypayUserInfo;
    @Resource
    private CallbackRunner callbackRunner;
    @Resource
    private PayAccountService payAccountService;
    /**
     * 开通平台渠道支付功能通知
     */
    @RequestMapping(value = "/fbank/openPay", method = RequestMethod.POST)
    public String openPayChannel(@RequestBody String body) {
        log.info("AccountChangeController#openPayChannel notify ,body={}", body);
        // 解析参数
        List<Object> openPayList = new ArrayList<>();
        try {
            openPayList = (List<Object>) JSONUtils.parse2Map(body, String.class, Object.class).get("body");
        }
        catch(Exception ex) {
            log.error(ex.getMessage() + ", body=" + body ,ex);
            return "TODO";
        }

        // 是否全部成功
        boolean isFullSuccess = true;
        for (Object openPayStr : openPayList) {
            try {
                // 更新状态
                Map<String, Object> stringStringMap = (Map<String, Object>) openPayStr;
                String fictiAccountNumber = String.valueOf(stringStringMap.get("fictiAccountNumber"));
                String powerId= String.valueOf(stringStringMap.get("piId"));
                // 是否进行微信开户意愿申请
                boolean isOpenAccountApplyment = true;

                ThirdUserInfo thirdUserInfo = thirdUserInfoService.getThirdUserInfoByThirdUserId(fictiAccountNumber);
                String accountId = thirdUserInfo.getUserId();
                List<OpenpayInfo> openpayInfos = openpayInfoService.queryUserInfoByAccountId(accountId, thirdUserInfo.getId());
                for (OpenpayInfo openpayInfo : openpayInfos) {
                    // 遍历查询的所有开通记录修改开通状态 开通的忽略跳过
                    if(Objects.equals(openpayInfo.getPowerId(), powerId) && openpayInfo.getStatus() != OpenPayStatusEnum.SUCCESS_PAY_CHANNEL.getStatus()) {
                        OpenpayInfo record = new OpenpayInfo();
                        record.setStatus(OpenPayStatusEnum.SUCCESS_PAY_CHANNEL.getStatus());
                        record.setAccountId(openpayInfo.getAccountId());
                        record.setThirdUserInfoId(openpayInfo.getThirdUserInfoId());
                        record.setPowerId(openpayInfo.getPowerId());
                        boolean isSuccess = openpayInfoService.updateStatusByPowerId(record) > 0;
                        if(!isSuccess) {
                            log.error("AccountChangeController#openPayChannel openpayService.updateStatusByPowerId fail. openPayStr:{}, openpayInfo:{}", openPayStr, JSONUtils.toJSON(openpayInfo));
                            isOpenAccountApplyment = false;
                        }
                    } else {
                        // 公众号、小程序 需要验证是否都配置了，若有没有配置的则不发送微信申请
                        if(FBankPowerIdEnum.WX_OFFICIAL.getPowerId().equals(openpayInfo.getPowerId())
                                || FBankPowerIdEnum.WX_MINI.getPowerId().equals(openpayInfo.getPowerId())) {
                            if(OpenPayStatusEnum.SUCCESS_PAY_CHANNEL.getStatus() != openpayInfo.getStatus()) {
                                isOpenAccountApplyment = false;
                            }
                        }
                    }
                }

                log.info("AccountChangeController#openPayChannel accountId:{} isOpenAccountApplyment:{}", accountId, isOpenAccountApplyment);
                if(isOpenAccountApplyment) {
                    // check 微信开户意愿状态
                    ApplyOpenAccountStatus param = new ApplyOpenAccountStatus();
                    param.setThirdUserId(thirdUserInfo.getThirdUserId());
                    param.setAccountId(accountId);
                    List<ApplyOpenAccountStatus> applyOpenAccountList = applyOpenAccountStatusService.selectByParam(param);
                    if(applyOpenAccountList.size() == 1) {
                        ApplyOpenAccountStatus applyOpenAccountStatus = applyOpenAccountList.get(0);
                        PayAccount payAccount = payAccountService.getPayAccountByAccountId(applyOpenAccountStatus.getAccountId());
                        ApplypayUserInfo applypayUserInfo = this.applypayUserInfo.queryUserInfoByAccountId(applyOpenAccountStatus.getAccountId());
                        if(applyOpenAccountStatus.getAuthorize() == OpenAccountAuthorizeStatusEnum.AUTHORIZE_STATE_AUTHORIZED.getStatus()) {
                            // 若授权了 则回调业务
                            callbackRunner.callback(payAccount.getBusinessUserId(), CallbackResultVo.TYPE_OPEN_ACCOUNT_SUCCESS, 0,0,null, applypayUserInfo.getCallback(), "");
                        }
                    }
                }
            }catch (Exception e) {
                log.error("AccountChangeController#openPayChannel update status fail. openPayStr:{}", openPayStr, e);
                isFullSuccess = false;
            }
        }

        return isFullSuccess ? "SUCCESS" : "FAIL";
    }
}
